package com.bootdo.wx.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaShopSpuService;
import cn.binarywang.wx.miniapp.api.impl.WxMaShopSpuServiceImpl;
import cn.binarywang.wx.miniapp.bean.shop.*;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopAddSpuResponse;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopBaseResponse;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaShopGetSpuResponse;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bootdo.common.config.WxMaConfiguration;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.dao.TaskDao;
import com.bootdo.common.domain.TaskDO;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.LiveExcelUtils;
import com.bootdo.wx.domain.GoodsGoodsDO;
import com.bootdo.wx.domain.GoodsLiveDO;
import com.bootdo.wx.domain.GoodsProductDO;
import com.bootdo.wx.service.GoodsGoodsService;
import com.bootdo.wx.service.GoodsImagesService;
import com.bootdo.wx.service.GoodsLiveService;
import com.bootdo.wx.service.GoodsProductService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 直播商品列表
 * 
 * @author long
 * @email 499626561@qq.com
 * @date 2021-05-09 18:07:52
 */
 
@Controller
@RequestMapping("/wx/goodsLive")
public class GoodsLiveController {
	@Autowired
	private GoodsLiveService goodsLiveService;
	@Autowired
	private GoodsGoodsService goodsGoodsService;
	@Autowired
	private WxMaProperties properties;

	@Autowired
	private GoodsImagesService goodsImagesService;
	@Autowired
	private GoodsProductService goodsProductService;
	@Autowired
	private TaskDao taskDao;

	@GetMapping()
	@RequiresPermissions("wx:goodsLive:goodsLive")
	String GoodsLive(){
	    return "wx/goodsLive/goodsLive";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:goodsLive:goodsLive")
	public PageUtils list(@RequestParam Map<String, Object> params) throws Exception {
	    params.put("delFlag","0");
	    params.put("sort","ca_at");
	    params.put("order","desc");
        //查询列表数据
        Query query = new Query(params);
	    if(params.containsKey("name")&&StringUtils.isNotBlank(params.get("name").toString())){
            List<GoodsLiveDO> goodsLiveList = goodsLiveService.likeList(query);
            List<Map<String,Object>> returnList = new ArrayList<>();
            if(goodsLiveList.size()>0){
				for (GoodsLiveDO goodsLiveDO : goodsLiveList) {
					Map<String, Object> stringObjectMap = BeanUtil.beanToMap(goodsLiveDO);
					GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
					if(goodsGoodsDO!=null){
						stringObjectMap.put("goodsName",goodsGoodsDO.getName());
						stringObjectMap.put("goodsImg",goodsGoodsDO.getImgurl());

					}else{
						stringObjectMap.put("goodsName","商品不存在");
						stringObjectMap.put("goodsImg","");
					}
					returnList.add(stringObjectMap);
				}
			}
            int total = goodsLiveList.size();
            PageUtils pageUtils = new PageUtils(returnList, total);
            return pageUtils;
		}

		List<GoodsLiveDO> goodsLiveList = goodsLiveService.list(query);
		List<Map<String,Object>> returnList = new ArrayList<>();
		if(goodsLiveList.size()>0){
			for (GoodsLiveDO goodsLiveDO : goodsLiveList) {
				Map<String, Object> stringObjectMap = BeanUtil.beanToMap(goodsLiveDO);
				GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
				if(goodsGoodsDO!=null){
					stringObjectMap.put("goodsName",goodsGoodsDO.getName());
					stringObjectMap.put("goodsImg",goodsGoodsDO.getImgurl());
				}else{
					stringObjectMap.put("goodsName","商品不存在");
					stringObjectMap.put("goodsImg","");
				}
				returnList.add(stringObjectMap);
			}
		}
		int total = goodsLiveService.count(query);
		PageUtils pageUtils = new PageUtils(returnList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:goodsLive:add")
	String add(){
	    return "wx/goodsLive/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:goodsLive:edit")
	String edit(@PathVariable("id") String id,Model model){
		GoodsLiveDO goodsLive = goodsLiveService.get(id);
		model.addAttribute("goodsLive", goodsLive);
		List<Map<String, Object>> maps = goodsGoodsService.queryAllForIdAndName(new HashMap<>());
		model.addAttribute("goodsList",maps);
		return "wx/goodsLive/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:goodsLive:add")
	public R save( GoodsLiveDO goodsLive)  {
	    goodsLive.setId(UuidUtil.get32UUID());
	    goodsLive.setDelFlag(0);
	    goodsLive.setCaAt(new Date());
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLive.getGoodsId());
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
		WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
		//商品轮播图
		Map<String,Object> imgMap = new HashMap<>();
		imgMap.put("address","0");
		imgMap.put("goodsId",goodsGoodsDO.getId());
		List<String> bannerList = goodsImagesService.getImgUrlByAddress(imgMap);
		imgMap.put("address","1");
		List<String> infoImgList = goodsImagesService.getImgUrlByAddress(imgMap);
		WxMaShopSpuInfo wxMaShopSpuInfo = new WxMaShopSpuInfo();
		wxMaShopSpuInfo.setTitle(goodsGoodsDO.getTitle());
		wxMaShopSpuInfo.setPath("/pages/details/details?id="+goodsGoodsDO.getId());
		wxMaShopSpuInfo.setBrandId(2100000000);
		wxMaShopSpuInfo.setOutProductId(goodsGoodsDO.getId());
		wxMaShopSpuInfo.setThirdCatId(goodsLive.getCatId());
		List<String> picList = new ArrayList<>();
		String qualificationPics = goodsLive.getQualificationPics();
		if(StringUtils.isNotBlank(qualificationPics)){
			picList.add(qualificationPics);
		}
		wxMaShopSpuInfo.setQualificationPics(picList);
		wxMaShopSpuInfo.setHeadImg(bannerList);
		WxMaShopSpuDescInfo wxMaShopSpuDescInfo = new WxMaShopSpuDescInfo();
		wxMaShopSpuDescInfo.setDesc(goodsGoodsDO.getCopywriting());
		wxMaShopSpuDescInfo.setImgList(infoImgList);
		wxMaShopSpuInfo.setDescInfo(wxMaShopSpuDescInfo);


		List<GoodsProductDO> productList = goodsProductService.getByGoodsId(goodsGoodsDO.getId());
		if(productList.size()<=0){
			return R.error("商品信息有误");
		}
		List<WxMaShopSkuInfo> skus = new ArrayList<>();
		for (GoodsProductDO goodsProductDO : productList) {
			WxMaShopSkuInfo wxMaShopSkuInfo = new WxMaShopSkuInfo();
			wxMaShopSkuInfo.setBarcode("");
			wxMaShopSkuInfo.setSkuCode(goodsProductDO.getSku());
			wxMaShopSkuInfo.setOutProductId(goodsGoodsDO.getId());
			wxMaShopSkuInfo.setOutSkuId(goodsProductDO.getId());
			wxMaShopSkuInfo.setMarketPrice(goodsProductDO.getPriceMarket().multiply(new BigDecimal("100")).intValue());
			wxMaShopSkuInfo.setSalePrice(goodsProductDO.getPrice().multiply(new BigDecimal("100")).intValue());
			wxMaShopSkuInfo.setStockNum(goodsProductDO.getStock());
			wxMaShopSkuInfo.setThumbImg(goodsProductDO.getIcon());

			//规格
			String spec = goodsGoodsDO.getSpec();
			if(StringUtils.isBlank(spec)||spec.equals("[]")){
				WxMaShopSkuAttribute wxMaShopSkuAttribute = new WxMaShopSkuAttribute();
				wxMaShopSkuAttribute.setAttrKey("");
				wxMaShopSkuAttribute.setAttrValue("");
				List<WxMaShopSkuAttribute> attributeList = new ArrayList<>();
				attributeList.add(wxMaShopSkuAttribute);
				wxMaShopSkuInfo.setSkuAttributeList(attributeList);
			}else{
				JSONArray specArray = JSONUtil.parseArray(spec);

				if(specArray.size()>0){
					List<WxMaShopSkuAttribute> attributeList = new ArrayList<>();
					Iterator<Object> iterator = specArray.iterator();
					while(iterator.hasNext()) {
						JSONObject specObject = (JSONObject)iterator.next();
						JSONArray spec_values = specObject.getJSONArray("spec_values");
						Iterator<Object> valuesIterator = spec_values.iterator();
						while(valuesIterator.hasNext()) {
							JSONObject valuesObject = (JSONObject)valuesIterator.next();

							WxMaShopSkuAttribute wxMaShopSkuAttribute = new WxMaShopSkuAttribute();
							wxMaShopSkuAttribute.setAttrKey(valuesObject.getStr("spec_name"));
							wxMaShopSkuAttribute.setAttrValue(valuesObject.getStr("spec_value_name"));
							attributeList.add(wxMaShopSkuAttribute);
						}
					}
					wxMaShopSkuInfo.setSkuAttributeList(attributeList);
				}else{
					WxMaShopSkuAttribute wxMaShopSkuAttribute = new WxMaShopSkuAttribute();
					wxMaShopSkuAttribute.setAttrKey("");
					wxMaShopSkuAttribute.setAttrValue("");
					List<WxMaShopSkuAttribute> attributeList = new ArrayList<>();
					attributeList.add(wxMaShopSkuAttribute);
					wxMaShopSkuInfo.setSkuAttributeList(attributeList);
				}

			}
			skus.add(wxMaShopSkuInfo);
		}
		wxMaShopSpuInfo.setSkus(skus);

		try {
			WxMaShopAddSpuResponse wxMaShopAddSpuResponse = wxMaShopSpuService.addSpu(wxMaShopSpuInfo);

		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		//添加任务表达式
		TaskDO taskDO = new TaskDO();
		taskDO.setBeanClass("com.bootdo.common.task.LiveKeepJop");
		taskDO.setCreateBy("系统生成");
		taskDO.setCreateDate(new Date());
		taskDO.setDescription("订阅消息预约前10分钟任务");
		DateTime newDate3 = DateUtil.offsetMinute(goodsLive.getStarAt(), -10); //前10分钟时间
		int year = newDate3.year();
		int month = newDate3.month()+1;
		int day = newDate3.dayOfMonth();
		int hour = newDate3.hour(true);
		int minute = newDate3.minute();
		int second = newDate3.second();
		int dayOfWeek = newDate3.dayOfWeek();
		//35 42 19 27 5 ?
		String cron = second + " "+minute+" "+hour+" "+day+ " "+month+" "+ "?";

		taskDO.setCronExpression(cron);
		taskDO.setJobGroup(goodsLive.getId());
		taskDO.setJobName("发送直播预约消息");
		taskDO.setJobStatus("1");
		taskDO.setMethodName("execute");


		taskDao.save(taskDO);


		if(goodsLiveService.save(goodsLive)>0){


			return R.ok();
		}

		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:goodsLive:edit")
	public R update( GoodsLiveDO goodsLive){
		goodsLive.setUpAt(new Date());
		goodsLiveService.update(goodsLive);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:goodsLive:remove")
	public R remove( String id){
		GoodsLiveDO goodsLiveDO = goodsLiveService.get(id);
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
		WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
		try {
			WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopSpuService.deleteSpu(-1, goodsLiveDO.getGoodsId());
			GoodsLiveDO goodsLive = goodsLiveService.get(id);
			goodsLive.setDelFlag(1);
			goodsLive.setUpAt(new Date());
			if(goodsLiveService.update(goodsLive)>0){
				return R.ok();
			}else{
				return R.error(wxMaShopBaseResponse.getErrmsg());
			}
		} catch (WxErrorException e) {
			e.printStackTrace();

		}

		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:goodsLive:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
	   if(ids.length>0){
			for (String string : ids) {
				GoodsLiveDO goodsLive = goodsLiveService.get(string);
				goodsLive.setDelFlag(1);
				goodsLive.setUpAt(new Date());
				goodsLiveService.update(goodsLive);
			}
		}
	
		return R.ok();
	}

	/**
	 * 获取审核状态
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/getShen/{id}")
	@RequiresPermissions("wx:goodsLive:edit")
	String getShen(@PathVariable("id") String id,Model model){
		GoodsLiveDO goodsLive = goodsLiveService.get(id);
		model.addAttribute("goodsLive", goodsLive);

			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
			//String responseContent = wxService.post("https://api.weixin.qq.com/shop/spu/get", GsonHelper.buildJsonObject(new Object[]{ "out_product_id", "93eb12e0c63d454d97cb302e40a0260c", "need_edit_spu", 1}));

			try {
				WxMaShopGetSpuResponse spu = wxMaShopSpuService.getSpu(goodsLive.getGoodsId(), 0);
				WxMaShopGetSpuResult spu1 = spu.getSpu();
				model.addAttribute("wxMaShopGetSpuResult", spu1);
			} catch (WxErrorException e) {
				e.printStackTrace();


		}


		return "wx/goodsLive/shen";
	}



	/***
	 * 撤回审核
	 * @param goodsLive
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delAudit")
	@RequiresPermissions("wx:goodsLive:edit")
	public R delAudit( GoodsLiveDO goodsLive){

		GoodsLiveDO goodsLiveDO = goodsLiveService.get(goodsLive.getId());
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
		WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
		try {
			WxMaShopBaseResponse wxMaShopBaseResponse  = wxMaShopSpuService.deleteSpuAudit(goodsGoodsDO.getId(), -1);
			return R.ok(0,wxMaShopBaseResponse.getErrmsg());
		} catch (WxErrorException e) {
			e.printStackTrace();
		}


		return R.ok();
	}

	/***
	 * 上架商品
	 * @param goodsLive
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/listingGoods")
	@RequiresPermissions("wx:goodsLive:edit")
	public R listingGoods( GoodsLiveDO goodsLive){

		GoodsLiveDO goodsLiveDO = goodsLiveService.get(goodsLive.getId());
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
		WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
		try {
			WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopSpuService.listingSpu(-1, goodsGoodsDO.getId());

			return R.ok(0,wxMaShopBaseResponse.getErrmsg());
		} catch (WxErrorException e) {
			e.printStackTrace();
		}


		return R.ok();
	}


	/***
	 * 下架商品
	 * @param goodsLive
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delistingGoods")
	@RequiresPermissions("wx:goodsLive:edit")
	public R delistingGoods( GoodsLiveDO goodsLive){

		GoodsLiveDO goodsLiveDO = goodsLiveService.get(goodsLive.getId());
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
		final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
		WxMaShopSpuService wxMaShopSpuService = new WxMaShopSpuServiceImpl(wxService);
		try {
			WxMaShopBaseResponse wxMaShopBaseResponse = wxMaShopSpuService.delistingSpu(-1, goodsGoodsDO.getId());

			return R.ok(0,wxMaShopBaseResponse.getErrmsg());
		} catch (WxErrorException e) {
			e.printStackTrace();
		}


		return R.ok();
	}


	/**
	 * 导出用户excel表格
	 */
	@RequestMapping( "/exportExcel")
	@RequiresPermissions("wx:memberUser:memberUser")
	public void exportExcel(HttpServletResponse response, HttpServletRequest request){
		try
		{
			Map<String, Object> query =  new HashMap<>();
			List<GoodsLiveDO> goodsLiveList = goodsLiveService.list(query);
			List<Map<String,Object>> returnList = new ArrayList<>();
			if(goodsLiveList.size()>0){
				for (GoodsLiveDO goodsLiveDO : goodsLiveList) {
					Map<String, Object> stringObjectMap = BeanUtil.beanToMap(goodsLiveDO);
					GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(goodsLiveDO.getGoodsId());
					if(goodsGoodsDO!=null){
						stringObjectMap.put("goodsName",goodsGoodsDO.getName());
						stringObjectMap.put("goodsImg",goodsGoodsDO.getImgurl());
					}else{
						stringObjectMap.put("goodsName","商品不存在");
						stringObjectMap.put("goodsImg","");
					}
					returnList.add(stringObjectMap);
				}
			}
			//这里设置的文件格式是application/x-excel
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("直播商品信息列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			LiveExcelUtils.exportLiverExcel(returnList, outputStream);
			if(outputStream != null) {
				outputStream.close();
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}





}
